package com.rbac.admin.controller.auth;
import com.rbac.admin.annotation.OperationLog;
import com.rbac.admin.common.result.Result;
import com.rbac.admin.dto.auth.LoginDTO;
import com.rbac.admin.dto.auth.LoginResultDTO;
import com.rbac.admin.service.auth.AuthService;
import com.rbac.admin.vo.system.UserVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 认证控制器
 *
 * @author rbac-admin
 * @since 2024-07-18
 */
@Tag(name = "认证管理", description = "认证管理相关接口")
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 登录
     */
    @Operation(summary = "登录")
    @PostMapping("/login")
    @OperationLog(module = "认证管理", type = "登录", value = "登录")

    public Result<LoginResultDTO> login(@RequestBody @Valid LoginDTO loginDTO) {
        try {
            LoginResultDTO resultDTO = authService.login(loginDTO);
            return Result.success("登录成功", resultDTO);
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }

    /**
     * 登出
     */
    @Operation(summary = "登出")
    @OperationLog(module = "认证管理", type = "登出", value = "登出")
    @PostMapping("/logout")
    public Result<Object> logout() {
        try {
            authService.logout();
            return Result.success("退出成功");
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }

    /**
     * 获取当前用户信息
     */
    @Operation(summary = "获取当前用户信息")
    @GetMapping("/info")
    public Result<UserVO> getUserInfo() {
        try {
            UserVO userVO = authService.getCurrentUserInfo();
            return Result.success(userVO);
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }

    /**
     * 刷新令牌
     */
    @Operation(summary = "刷新令牌")
    @PostMapping("/refresh")
    public Result<String> refreshToken(@RequestParam String refreshToken) {
        try {
            String token = authService.refreshToken(refreshToken);
            return Result.success("刷新成功", token);
        } catch (Exception e) {
            return Result.failed(e.getMessage());
        }
    }
}